const express = require('express');
const router = express.Router();
const MpUser = require('../models/MpUser');
const moment = require('moment');

// 粉丝列表页面
router.get('/', async (req, res) => {
  try {
    // 获取分页参数
    const page = parseInt(req.query.page) || 1;
    const limit = 10;  // 每页显示10条

    // 获取搜索参数
    const searchParams = {
      id: req.query.id,
      nickname: req.query.nickname,
      appid: req.query.appid,
      openid: req.query.openid,
      unionid: req.query.unionid,
      status: req.query.status,
      tag: req.query.tag,
      createAt: req.query.createAt
    };

    // 获取总记录数
    const total = await MpUser.count(searchParams);
    
    // 计算总页数
    const totalPages = Math.ceil(total / limit);
    
    // 获取当前页数据
    const mpusers = await MpUser.findAll(page, limit, searchParams);

    // 生成分页链接数组，最多显示5个页码
    const pages = [];
    let startPage = Math.max(1, page - 2);
    let endPage = Math.min(totalPages, startPage + 4);
    
    // 如果结束页码不够5个，调整起始页码
    if (endPage - startPage < 4) {
      startPage = Math.max(1, endPage - 4);
    }

    for (let i = startPage; i <= endPage; i++) {
      pages.push({
        number: i,
        active: i === page,
        url: `?page=${i}${Object.entries(searchParams)
          .filter(([key, value]) => value)
          .map(([key, value]) => `&${key}=${encodeURIComponent(value)}`)
          .join('')}`
      });
    }

    res.render('mpusers/list', {
      mpusers,
      searchParams,
      pagination: {
        current: page,
        total: totalPages,
        pages,
        prev: page > 1 ? page - 1 : null,
        next: page < totalPages ? page + 1 : null,
        firstPage: page > 3 ? 1 : null,  // 添加首页链接
        lastPage: page < totalPages - 2 ? totalPages : null  // 添加尾页链接
      }
    });
  } catch (err) {
    console.error('获取粉丝列表失败:', err);
    res.status(500).send('获取粉丝列表失败');
  }
});

// 添加粉丝页面
router.get('/add', (req, res) => {
  res.render('mpusers/add');
});

// 处理添加粉丝
router.post('/add', async (req, res) => {
  try {
    await MpUser.create(req.body);
    res.redirect('/mpusers');
  } catch (err) {
    res.status(500).send('添加粉丝失败');
  }
});

// 编辑粉丝页面
router.get('/edit/:id', async (req, res) => {
  try {
    const mpusers = await MpUser.findAll(1, 1, { id: req.params.id });
    if (mpusers.length === 0) {
      return res.status(404).send('粉丝不存在');
    }
    res.render('mpusers/edit', { mpuser: mpusers[0] });
  } catch (err) {
    res.status(500).send('服务器错误');
  }
});

// 处理编辑粉丝
router.post('/edit/:id', async (req, res) => {
  try {
    await MpUser.update(req.params.id, req.body);
    res.redirect('/mpusers');
  } catch (err) {
    res.status(500).send('更新粉丝失败');
  }
});

// 删除粉丝
router.post('/delete/:id', async (req, res) => {
  try {
    await MpUser.delete(req.params.id);
    res.redirect('/mpusers');
  } catch (err) {
    res.status(500).send('删除粉丝失败');
  }
});

module.exports = router; 